package conn

import (
	"gitee.com/cooge/impush/core"
	"errors"
	"gitee.com/cooge/impush/gutil"
	"gitee.com/cooge/impush/message"
	"net"
	"sync"
	"time"
	"gitee.com/cooge/impush/xhttp/cache"
)

type HttpConn struct {
	UserId  string
	list    *gutil.Linklist
	lock    *sync.RWMutex
	address string
	InTime time.Time
	DealTime int
}

func DealHttpConn(conn *net.TCPConn, userId string, deal int) *HttpConn {
	hc := NewHttpConn(userId)
	ihc := core.GetSetOneUser(userId, hc)
	xhc, ok := ihc.(*HttpConn)
	if ok {
		xhc.dealConn(conn, deal,userId)
		xhc.InTime =time.Now()
		xhc.DealTime = deal
		return xhc
	} else {
		core.DeleteUser(userId, xhc)
	}
	return nil
}

func NewHttpConn(userId string) *HttpConn {
	var hc HttpConn
	hc.UserId = userId
	hc.lock = new(sync.RWMutex)
	return &hc
}
func (this *HttpConn)ConnNum()int{
	return this.list.Len()
}
func (this *HttpConn)ConnArray()[]interface{}{
	return this.list.GetAllArray()
}

func (this *HttpConn) SendMessage(msg *message.Message) (int, error) {
	is := this.list.GetAllArray()
	for _, v := range is {
		hv, ok := v.(*HTCPconn)
		if ok {
			num, err := hv.SendMessage(msg)
			if err == nil {
				return num, err
			}
		}
	}
	cache.AddMessgeCache(this.UserId, msg)
	return 0, nil
}

func (this *HttpConn) SendMessages(msgs []*message.Message) (int, error) {
	is := this.list.GetAllArray()
	for _, v := range is {
		hv, ok := v.(*HTCPconn)
		if ok {
			num, err := hv.SendMessages(msgs)
			if err == nil {
				return num, err
			}
		}
	}
	return 0, errors.New("error fail")
}

func (this *HttpConn) GetUser() string {
	return this.address
}

func (this *HttpConn)  Close(userId string)error{
	core.DeleteUser(userId,this)
	return nil
}

func (this *HttpConn) dealConn(conn *net.TCPConn, deal int,userId string) {
	this.lock.Lock()
	nhp := NewHTCPconn(conn, deal,userId)
	if this.list == nil {
		this.list = gutil.NewLinkList()
	}
	this.list.Add(nhp)
	nhp.Start(func(pconn *HTCPconn) {
		this.list.Delete(pconn)
	})
	this.address = conn.RemoteAddr().String()
	this.lock.Unlock()
}
